package com.tianji.learning.DelayQueue;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;
import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@Data
public class DelayTask<T> implements Delayed, Serializable {

    private Long deadLineNanos; // 延时执行时间
    private T data; // 延时任务的数据

    public DelayTask(Duration duration, T data) {
        this.deadLineNanos = System.nanoTime() + duration.toNanos();
        this.data = data;
    }

    // 用来获取队列中每个任务 距离当前时间还有多久被执行的时间
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(deadLineNanos - System.nanoTime(),0),TimeUnit.NANOSECONDS);
    }

    // 对延时任务队列中的每个任务进行排序
    @Override
    public int compareTo(Delayed o) {
        long diff = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        return diff >0 ? 1 :diff == 0 ? 0 : -1;
    }
}
